package nl.avans.osgi.ds.client.console;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import nl.avans.osgi.ds.client.datagrid.PersonDataGrid;
import nl.avans.osgi.ds.persistence.person.data.PersonService;
import nl.avans.osgi.ds.persistence.person.model.Person;

public class ConsoleService {

    private PersonDataGrid personDataGrid;
    private PersonService personService;
    private ConsoleRunner runner;

    protected void activate(Map<String , Object> config) {
        System.out.println("ConsoleService activated.");
        getPersondata();
        runner = new ConsoleRunner();
        runner.start();
    }
    
    private void getPersondata() {
        if (personService == null) {
            System.out.println("Console client: No PersonService found.");
            return;
        }
        if (personDataGrid == null) {
            System.out.println("Console client: No PersonDataGrid found.");
            return;
        }
        
        List<Person> persons = personService.getEmployees();
        personDataGrid.setData(persons);
        
    }

    protected void deactivate() {
        runner.interrupt();
        System.out.println("ConsoleService deactivated.");
    }
    
    protected void setPersonDataGrid(PersonDataGrid dataGrid) {
        this.personDataGrid = dataGrid;
    }

    protected void unsetPersonDataGrid(PersonDataGrid dataGrid) {
        this.personDataGrid = null;
    }

    protected void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    protected void unsetPersonService(PersonService personService) {
        this.personService = null;
    }

    private class ConsoleRunner extends Thread {

        private boolean active = true;

        @Override
        public void run() {
            System.out.println("type exit to exit");
            String input = "";

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                while (active) {
                    System.out.println("Enter some text.");
                    input = reader.readLine();

                    if ("exit".equals(input)) {
                        active = false;
                        deactivate();
                        break;
                    }
                    System.out.println("Your input was: " + input);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
